import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Button, Modal, Input } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import SelectForm from '@/components/SelectForm';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import ManageList from '@/components/ManageList';
import AntdFormItem from '@/components/AntdFormItem';
import AntdForm from '@/components/AntdForm';
import FileImport from '@/components/FileImport';
import AntdInput from '@/components/AntdInput';
import TableButtons from '@/components/TableButtons';
import StandardTable from '@/components/StandardTable';
import FileReader from '@/components/FileReader';
import AdSearch from '@/components/AdSearch';
import { allDictList } from '@/utils/constans';
import SearchSelect from '@/components/SearchSelect';
import AntdDatePicker from '@/components/AntdDatePicker';
import TrailUpdateInfo from './TrailUpdateInfo';
import { queryDict } from '@/utils/common';
import prompt from '@/components/Prompt';
import {
  allDispatchType,
  codes,
  trailNodeStatus,
  trailType,
  statusAndType,
  formatStatusAndType,
} from './utils';
import styles from './trailUpdate.less';

const { confirm } = Modal;
const dateFormat = 'YYYY-MM-DD HH:mm';

@ManageList
@connect(({ trailUpdate, loading, component }) => ({
  trailUpdate,
  trailUpdateList: trailUpdate.trailUpdateList,
  dictObject: component.dictObject,
  searchValue: component.searchValue,
  loading: loading.effects[allDispatchType.list],
}))
@Form.create()
export default class TrailUpdate extends Component {
  constructor(props) {
    super(props);
    const {
      form: { getFieldDecorator },
    } = props;
    this.commonParams = {
      getFieldDecorator,
    };
    this.state = {
      selectedRows: [],
      disabled: false,
      visibleFile: false,
      existOrders: false,
      orderNum: '',
      showTips: '',
    };
  }
  className = 'trailupdate-table';
  //表格显示提示：
  showTipsFun = val => {
    this.setState({
      showTips: val,
    });
  };
  onRef = (ref) => {
    this.child = ref;
  }
  //新增
  handleAdd = () => {
    this.child.handleAdd();
  };
  //移除
  removeInfo = e => {
    e.stopPropagation();
    confirm({
      title: '确定要移除数据吗？',
      content: ' ',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        const { orderNum, selectedRows } = this.state;
        const { trailUpdateList } = this.props;
        const list = trailUpdateList[orderNum].list;
        console.log('list', list, 'selectedRows:', selectedRows)
        if (selectedRows.length == list.length) {
          prompt({
            content: '订单轨迹不能全部删除，至少保留一条数据',
            type: 'warn'
          })
          return;
        }
        const deleteIds = selectedRows.map(v => v.id);
        const newData = trailUpdateList[orderNum].list.filter(item => !deleteIds.includes(item.id));
        this.saveAllValue({ trailUpdateList: { [orderNum]: { list: newData } } });
        this.handleStateChange([{ selectedRows: [], showTips: true }]);
      },
    });

  };

  getInfoData = () => {
    const { trailUpdateList } = this.props;
    const { orderNum } = this.state;
    let newData = [];
    if (trailUpdateList[orderNum]) {
      const data = trailUpdateList[orderNum].list;
      newData = data.map(item => ({ ...item }));
    }
    return newData;
  };

  getRowByKey(id, newData) {
    const data = this.getInfoData();
    return (newData || data).filter(item => item.id === id)[0];
  }

  saveAllValue = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.value,
      payload: payload || {},
    });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };
  /* 表格表单数据处理---end---*/

  /**
   * form 查找条件 重置
   */
  handleFormReset = () => {
    const { form } = this.props;
    this.setState({
      orderNum: '',
    });
    form.resetFields();
    // this.getTrailUpdateList({});
  };

  /**
   * form 查找条件 查询
   */
  handleSearch = formValues => {
    const { orderNo } = formValues;
    this.child.getTrailUpdateList({ orderNo });
    if (!orderNo) {
      prompt({ content: '请输入订单号', type: 'warn' });
      return;
    }
    this.setState({
      orderNum: orderNo,
    });
  };

  /**
   * table 表格 分页操作
   */
  handleStandardTableChange = param => {
    // this.getTrailUpdateList(param);
  };

  //导入
  handleImportFile = () => {
    const { visibleFile } = this.state;
    this.setState({ visibleFile: !visibleFile });
  };
  //保存：
  saveData = () => {
    const { form, trailUpdateList, dispatch } = this.props;
    const { orderNum } = this.state;
    const orderNo = orderNum;
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;

      const params = trailUpdateList[orderNum].list;
      dispatch({
        type: allDispatchType.save,
        payload: params,
        callback: data => {
          // if (!data) return;
          // this.getTrailUpdateList({ orderNo });
        },
      });
    });
  };

  render() {
    const { form, loading, trailUpdateList } = this.props;
    const { selectedRows, visibleFile, showTips, existOrders } = this.state;
    const commonParams = {
      getFieldDecorator: form.getFieldDecorator,
    };
    const { orderNum } = this.state;
    const data = trailUpdateList[orderNum] || {list:[]};

    const firstFormItem = (
      <AntdFormItem label="订单编号" code="orderNo" {...commonParams}>
        <Input />
      </AntdFormItem>
    );
    const preTitle = showTips && (
      <div style={{ color: 'red', marginLeft: 30, lineHeight: '32px' }}>
        提示：<span>当前数据有变化，请注意保存</span>
      </div>
    );

    const selectFormParams = {
      firstFormItem,
      form,
      className: this.className,
      handleFormReset: null,
      handleSearch: this.handleSearch,
      toggleForm: expandForm => {
        this.handleStateChange([{ expandForm }]);
      },
      code: codes.select,
    };

    const tableButtonsParams = {
      handleAdd: existOrders ? this.handleAdd : '',
      code: codes.add,
      buttons: (
        <>
          <AdButton
            onClick={e => {
              this.removeInfo(e);
            }}
            ghost
            disabled={selectedRows.length === 0}
            text="移除"
            type="danger"
            code={codes.remove}
          />
          <AdButton
            style={{ marginLeft: 8 }}
            onClick={() => this.handleImportFile()}
            text="导入"
            code={codes.import}
          />
          {preTitle}
        </>
      ),
    };

    return (
      <div className="cus-ant-trail-page">
        <FileImport
          visibleFile={visibleFile}
          handleCancel={() => {
            this.handleImportFile();
          }}
          urlImport={`track-order/importTrack`}
          urlCase={`template/download?fileName=轨迹更新导入模板.xlsx`}
          // queryData={[this.getSelectList]}
          accept=".xls,.xlsx"
        />
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <TrailUpdateInfo
          orderNo={orderNum}
          onRef={this.onRef}
          checkOrder={existOrders => this.handleStateChange([existOrders])}
          selectedRows={selectedRows}
          onSelectRow={selectedRows => this.handleStateChange([{ selectedRows }])}
          showTipsFun={this.showTipsFun}
        />
      </div>
    );
  }
}
